package com.tim.helper.analysis.shp;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.tim.util.SwaggerJsonUtil;
import lombok.Data;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.junit.Test;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

/**
 * Date: 2023/8/22 9:42
 *
 * @Author: Tim
 * @Description: 读取swagger，生成gateway文件
 */
public class TsfGatewayHelper {
    @Test
    public void genJson() throws IOException {
        String swaggerUrl = "http://localhost:8801/v2/api-docs";
        String serviceName = "shpMall";
        String destDir = "C:\\Users\\PC\\tsf\\gateway\\";
        // 以下不改动
        JSONObject swaggerJson = SwaggerJsonUtil.getSwaggerJson(swaggerUrl);
        String groupJsonInfo = "{\n" +
                "        \"gatewayName\":\"山海平中台网关\",            //部署组名称\n" +
                "        \"gatewayGroupId\":\"shp-gateway\",     //部署组ID\n" +
                "        \"reversion\":24,\n" +
                "        \"updatedTime\":\"2021-03-29 11:56:52\",\n" +
                "        \"result\":[\n" +
                "            {\n" +
                "                \"groupId\":\"local-gateway\",      //网关分组ID\n" +
                "                \"groupName\":\"本地网关\",          //网关分组名称\n" +
                "                \"groupContext\":\"/sic\", //网关分组 context\n" +
                "                \"authMode\":\"none\",\n" +
                "                \"groupType\":\"ms\"\n" +
                "            }]\n" +
                "}";
        String apiJsonInfo = "{\n" +
                "        \"gatewayName\":\"山海平中台网关\",                  //部署组名称\n" +
                "        \"gatewayGroupId\":\"shp-gateway\",           //部署组ID\n" +
                "        \"reversion\":80,\n" +
                "        \"updatedTime\":\"2021-03-29 11:56:52\",\n" +
                "        \"result\":[]\n" +
                "    }";
        List<ApiResult> list = new ArrayList<>();
        String apiResultInfo = "{\n" +
                "                \"apiId\":\""+serviceName+ RandomUtils.nextInt()+"\",              //网关分组 API 的 ID\n" +
                "                \"groupId\":\"local-gateway\",            //网关分组ID（与 group.json 中的 groupId 保持一致时会认为该 API 属于该网关分组）\n" +
                "                \"path\":\"\",              //网关分组 API 的路径（也就是下游微服务的 API）\n" +
                "                \"method\":\"\",\n" +
                "                \"serviceName\":\""+serviceName+"\",       //网关下游的微服务名（也就是下游微服务的名称）\n" +
                "                \"namespaceId\":\"shp-"+ RandomUtils.nextInt()+"\",\n" +
                "                \"namespaceName\":\"shp"+"\",\n" +
                "                \"usableStatus\":\"enabled\",\n" +
                "                \"pathMapping\":\"\",\n" +
                "                \"apiType\":\"ms\"\n" +
                "            }";
        JSONObject paths = swaggerJson.getJSONObject("paths");
        for(String path : paths.keySet()){
            JSONObject pathJson = paths.getJSONObject(path);
            ApiResult item = JSON.parseObject(apiResultInfo, ApiResult.class);
            item.setPath(path);
            String method = pathJson.containsKey("post") ? "POST" : "GET";
            item.setMethod(method);
            item.setPathMapping(path);
            list.add(item);
        }
        ApiJson apiJson = JSONObject.parseObject(apiJsonInfo, ApiJson.class);
        apiJson.setResult(list);
        apiJsonInfo = JSON.toJSONString(apiJson);

        File destDirFile = new File(destDir);
        if(!destDirFile.exists()){
            destDirFile.mkdirs();
        }
        System.out.println(destDir);
        if(StringUtils.isNotBlank(groupJsonInfo)){
            groupJsonInfo = JSONUtil.formatJsonStr(groupJsonInfo);
            Files.write(Paths.get(destDir, "group.json"), groupJsonInfo.getBytes());
        }
        if(StringUtils.isNotBlank(apiJsonInfo)){
            apiJsonInfo = JSONUtil.formatJsonStr(apiJsonInfo);
            Files.write(Paths.get(destDir, "api.json"), apiJsonInfo.getBytes());
        }

    }

    /*
    {
        "gatewayName":"test-group",            //部署组名称
        "gatewayGroupId":"group-yrlkqnly",     //部署组ID
        "reversion":24,
        "updatedTime":"2021-03-29 11:56:52",
        "result":[
            {
                "groupId":"grp-60khzyb4",      //网关分组ID
                "groupName":"group1",          //网关分组名称
                "groupContext":"/test_group1", //网关分组 context
                "authMode":"none",
                "groupType":"ms"
            },
            {
                "groupId":"grp-sh1b4f4w",
                "groupName":"group2",
                "groupContext":"/test_group2",
                "authMode":"none",
                "groupType":"ms"
            }
        ]
    }
     */
    @Data
    static class GroupJson {
        /**
         * reversion
         */
        private String reversion;

        /**
         * result
         */
        private List<GroupResult> result;

        /**
         * updatedTime
         */
        private String updatedTime;

        /**
         * 部署组名称
         */
        private String gatewayName;

        /**
         * 部署组ID
         */
        private String gatewayGroupId;


    }

    @Data
    static class GroupResult {
        /**
         * authMode
         */
        private String authMode;

        /**
         * 网关分组名称
         */
        private String groupName;

        /**
         * groupType
         */
        private String groupType;

        /**
         * 网关分组 context
         */
        private String groupContext;

        /**
         * 网关分组ID
         */
        private String groupId;


    }

    /*
    {
        "gatewayName":"test-group",                  //部署组名称
        "gatewayGroupId":"group-yrlkqnly",           //部署组ID
        "reversion":80,
        "updatedTime":"2021-03-29 11:56:52",
        "result":[
            {
                "apiId":"api-c5zjvdbq",              //网关分组 API 的 ID
                "groupId":"grp-60khzyb4",            //网关分组ID（与 group.json 中的 groupId 保持一致时会认为该 API 属于该网关分组）
                "path":"/echo/{param}",              //网关分组 API 的路径（也就是下游微服务的 API）
                "method":"GET",
                "serviceName":"provider-demo",       //网关下游的微服务名（也就是下游微服务的名称）
                "namespaceId":"namespace-v6m6pp5a",
                "namespaceName":"test_namespace",
                "usableStatus":"enabled",
                "pathMapping":"/echo/{param}",
                "apiType":"ms"
            },
            {
                "apiId":"api-lc5cxghw",
                "groupId":"grp-60khzyb4",
                "path":"/echo/slow/{param}",
                "method":"GET",
                "serviceName":"provider-demo",
                "namespaceId":"namespace-v6m6pp5a",
                "namespaceName":"test_namespace",
                "usableStatus":"enabled",
                "pathMapping":"/echo/slow/{param}",
                "apiType":"ms"
            }
        ]
    }
     */
    @Data
    static class ApiJson {
        /**
         * reversion
         */
        private String reversion;

        /**
         * result
         */
        private List<ApiResult> result;

        /**
         * updatedTime
         */
        private String updatedTime;

        /**
         * 部署组名称
         */
        private String gatewayName;

        /**
         * 部署组ID
         */
        private String gatewayGroupId;



    }

    @Data
    static class ApiResult {
        /**
         * usableStatus
         */
        private String usableStatus;

        /**
         * 网关分组 API 的路径（也就是下游微服务的 API）
         */
        private String path;

        /**
         * method
         */
        private String method;

        /**
         * namespaceId
         */
        private String namespaceId;

        /**
         * 网关分组ID（与 group.json 中的 groupId 保持一致时会认为该 API 属于该网关分组）
         */
        private String groupId;

        /**
         * pathMapping
         */
        private String pathMapping;

        /**
         * 网关下游的微服务名（也就是下游微服务的名称）
         */
        private String serviceName;

        /**
         * 网关分组 API 的 ID
         */
        private String apiId;

        /**
         * namespaceName
         */
        private String namespaceName;

        /**
         * apiType
         */
        private String apiType;


    }
}
